package org.itzheng.myrxframe.http.retrofit.utils;

import android.support.annotation.NonNull;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import org.itzheng.myrxframe.http.ApiUrl;
import org.itzheng.myrxframe.http.retrofit.converter.FastJsonConverterFactory;
import org.itzheng.myrxframe.http.retrofit.interceptor.LogInterceptor;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import retrofit2.Retrofit;

/**
 * Title:<br>
 * Description: <br>
 *
 * @email ItZheng@ZoHo.com
 * Created by itzheng on 2019-4-8.
 */
public class RetrofitClient {
    /**
     * 获取默认的 Retrofit 不带log
     *
     * @return
     */
    @NonNull
    public static Retrofit getRetrofit() {
        return getRetrofit(false);
    }

    /**
     * 获取默认的 Retrofit
     *
     * @param isDebug 是否带log
     * @return
     */
    @NonNull
    public static Retrofit getRetrofit(boolean isDebug) {
        return getRetrofit(getOkHttpClient(isDebug));
    }

    /**
     * 通过自定义 Okhttp 获取 Retrofit，主要用于监听下载进度
     *
     * @param okHttpClient
     * @return
     */
    @NonNull
    public static Retrofit getRetrofit(OkHttpClient okHttpClient) {
        return new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(ApiUrl.BaseUrl)
                //添加GSON解析：返回数据转换成GSON类型
//                .addConverterFactory(GsonConverterFactory.create())
                //使用自己创建的fastJson
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//支持RxJava
                .build();
    }

    /**
     * 获取 OkHttpClient
     *
     * @param isDebug 是否有 log
     * @return
     */
    @NonNull
    public static OkHttpClient getOkHttpClient(boolean isDebug) {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
                .readTimeout(ApiUrl.DEFAULT_SECONDS_TIME_OUT, TimeUnit.SECONDS)//设置读取超时时间
                .connectTimeout(ApiUrl.DEFAULT_SECONDS_TIME_OUT, TimeUnit.SECONDS)//设置请求超时时间
                .writeTimeout(ApiUrl.DEFAULT_SECONDS_TIME_OUT, TimeUnit.SECONDS)//设置写入超时时间
//                .addInterceptor(new LogInterceptor())//添加打印拦截器
                .retryOnConnectionFailure(true);//设置出现错误进行重新连接。

        if (isDebug) {
            builder.addInterceptor(new LogInterceptor());//添加打印拦截器
        }
        return builder.build();
    }

}
